import Vue from 'vue'
import { verifyToken, getAuthDomain, getInfo } from '@/api/login'
import { getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const user = {
  state: {
    authUrl: '',
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: getUserInfo() || {}
  },

  mutations: {
    SET_AUTHURL: (state, url) => {
      state.authUrl = url
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 获取统一认证地址
    GetAuthUrl ({ commit }) {
      return getAuthDomain().then(res => {
        commit('SET_AUTHURL', res.content)
        return Promise.resolve(res.content)
      }).catch(() => {
        commit('SET_AUTHURL', '')
        return Promise.resolve('')
      })
    },

    // 登录
    Login ({ commit }, tk) {
      return verifyToken({ code: tk }).then(res => {
        const data = res.content || {}
        commit('SET_INFO', data)
        commit('SET_TOKEN', tk)
        Vue.ls.set(ACCESS_TOKEN, tk)
        setUserInfo(data)
        return Promise.resolve(res)
      }).catch(res => {
        return Promise.reject(res)
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return getInfo().then(response => {
        const result = response.content
        commit('SET_INFO', result)
        return Promise.resolve(result)
      }).catch(error => {
        return Promise.reject(error)
      })
    },

    // 登录退出
    Logout ({ state, commit }, { isReqLogOut, path }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        // commit('SET_INFO', {})
        removeUserInfo()
        Vue.ls.remove(ACCESS_TOKEN)
        const href = path || location.href
        let url = `${state.authUrl}/#/user/${isReqLogOut ? 'login' : 'auth'}?appId=6&corpId=1&redirectUrl=${encodeURIComponent(href)}`
        if (isReqLogOut) {
          url = `${state.authUrl}/api/user/logout?redirectUrl=${url}`
        }
        location.href = url
        resolve(true)
      })
    }
  }
}

export default user
